package cn.tjad.tjad2.module.document.adapter;

import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;

import cn.tjad.tjad2.R;
import cn.tjad.tjad2.module.common.adapter.SimpleRecyclerViewAdapter;
import cn.tjad.tjad2.data.event.OnCheckedEvent;
import cn.tjad.tjad2.module.common.viewholder.EmptyViewHolder;
import cn.tjad.tjad2.module.common.viewholder.SimpleBaseViewHolder;
import cn.tjad.tjad2.module.document.viewholder.PermissionBodySelectViewHolder;

public class PermissionBodySelectAdapter extends SimpleRecyclerViewAdapter<Serializable> {

    private int checkedPosition = -1;

    public PermissionBodySelectAdapter(List<Serializable> data) {
        super(data);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void fillEmptyViewData(EmptyViewHolder holder) {
        holder.setData("无成员", 0);
    }

    @Override
    protected SimpleBaseViewHolder<Serializable> onCreateNormalViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.permission_body_select_item, parent, false);
        PermissionBodySelectViewHolder viewHolder = new PermissionBodySelectViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull SimpleBaseViewHolder<Serializable> holder, int position) {
        super.onBindViewHolder(holder, position);
        if (holder instanceof PermissionBodySelectViewHolder) {
            ((PermissionBodySelectViewHolder) holder).setChecked(position == checkedPosition);
        }
    }

    public int getCheckedPosition() {
        return checkedPosition;
    }

    public void setCheckedPosition(int checkedPosition) {
        this.checkedPosition = checkedPosition;
        notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OnCheckedEvent event) {
        setCheckedPosition(event.getCheckedPosition());
    }

    public void onDestroy() {
        EventBus.getDefault().unregister(this);
    }
}
